package com.fjzx.androidframe.network.interceptor;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * SSO 单点登录使用的拦截器，以绕过单点登录重定向
 *
 * @author xiongyongcong
 */
public class SsoMobileInterceptor implements Interceptor {
    private static final String SUFFIX_MOBILE_REQUEST = "_REQUEST_SOURCE=MOBILE";
    private static final String QUESTION_MARK = "?";
    private static final String AND_MARK = "&";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        Request newRequest = addParam(oldRequest);
        return chain.proceed(newRequest);
    }

    private Request addParam(Request oldRequest) {
        // 添加一个请求参数
        String url = oldRequest.url().toString();
        if (!url.endsWith(SUFFIX_MOBILE_REQUEST)) {
            if (url.contains(QUESTION_MARK)) {
                url = url + AND_MARK + SUFFIX_MOBILE_REQUEST;
            } else {
                url = url + QUESTION_MARK + SUFFIX_MOBILE_REQUEST;
            }
        }
        Request newRequest = oldRequest.newBuilder()
                .url(url)
                .build();
        return newRequest;
    }
}
